<?php

namespace maotool\orm\mapper;

use maotool\file\FileUtil;
use maotool\util\ArrayUtil;
use maotool\util\SqlFormatterUtil;
use maotool\util\TreeUtil;
use maotool\util\XmlUtil;

class MapperLoader
{

    /**
     * 解析器
     * @param $name
     * @param $path
     * @param null $params
     * @return array
     */
    public static function parse($name, $path, $params = null)
    {
        $mapper = self::mapper($path);
        $element = ArrayUtil::filterOne($mapper["childNodes"], function ($item, $name) {
            if (isset($item["attributes"]["id"])) {
                if ($item["attributes"]["id"] == $name) {
                    return true;
                }
            }
            return false;
        }, $name);
        $TagProcessor = new MapperTagProcessor();
        $result = $TagProcessor->loadElement($element, $params);
        $result["sql"] = SqlFormatterUtil::compress($result["sql"]);
        return $result;
    }

    /**
     * 读取 mapper
     * @param $path
     * @return mixed|null
     */
    private static function mapper($path)
    {
        $treeXml = XmlUtil::toArray(FileUtil::read($path));
        $mappers = TreeUtil::findAll($treeXml, "nodeName", "mapper", ["children" => "childNodes"]);
        foreach ($mappers as $mapper) {
            if (count($mapper["childNodes"]) == 0) {
                continue;
            }
            return $mapper;
        }
        return null;
    }

    /**
     * 读取映射类
     * @param $path
     * @return object
     */
    public static function object($path)
    {
        $mapper = self::mapper($path);
        $object = FileUtil::read("maotool:/src/main/php/maotool/orm/mapper/MapperObject.php");
        $className = $mapper["attributes"]["class"];
        $namespace = $mapper["attributes"]["namespace"];
        $object = str_replace("<?php", "", $object);
        $object = str_replace("namespace maotool\orm\mapper;", "namespace " . $namespace . ";", $object);
        $object = str_replace("class MapperObject", "class " . $className, $object);
        $object = str_replace("return new MapperObject();", "return new " . $className . "();", $object);
        $path = str_replace("\\", "/", $path);
        $object = str_replace("private static \$path = \"\";", "private static \$path = \"" . base64_encode($path) . "\";", $object);
        return eval($object);
    }

}